<template>
  <div class="product-detail">
    <a-steps :current="current" class="steps">
      <a-step v-for="item in steps" :key="item.title" :title="item.title" />
    </a-steps>
    <div class="steps-content">
      <BasicDetail v-show="current === 0" ref="basic" />
      <SaleDetail v-show="current === 1" ref="sale" />
    </div>
    <div class="steps-action">
      <a-button v-if="current < steps.length - 1" type="primary" @click="next">
        下一步
      </a-button>
      <a-button
        v-if="current == steps.length - 1"
        type="primary"
        @click="submit"
      >
        完成
      </a-button>
      <a-button v-if="current > 0" style="margin-left: 8px" @click="prev">
        上一步
      </a-button>
    </div>
  </div>
</template>

<script>
import { add, detail, edit } from '@/api/product';
import BasicDetail from './BasicDetail.vue';
import SaleDetail from './SaleDetail.vue';

export default {
  components: {
    BasicDetail,
    SaleDetail,
  },
  data() {
    return {
      current: 0,
      steps: [
        {
          title: '填写商品基本信息',
        },
        {
          title: '填写商品销售信息',
        },
      ],
    };
  },
  mounted() {
    this.unwatch = this.$watch(
      () => this.$route.params.id,
      async (id) => {
        if (id) {
          //  编辑详情，读取信息
          this.edit = true;
          const res = await detail(id);
          this.info = res;
          this.$refs.basic.init(res);
          this.$refs.sale.init(res);
        } else {
          this.edit = false;
          this.$refs.basic.reset();
          this.$refs.sale.reset();
        }
      },
      {
        immediate: true,
      }
    );
  },
  destroyed() {
    this.unwatch();
  },
  methods: {
    next() {
      this.$refs.basic.validate((valid) => {
        if (valid) this.current += 1;
      });
    },
    prev() {
      this.current -= 1;
    },
    submit() {
      this.$refs.basic.validate(async (valid) => {
        if (valid) {
          if (this.edit) {
            await edit({
              ...this.$refs.basic.form,
              ...this.$refs.sale.form,
            });
            this.$message.success('修改成功！');
          } else {
            await add({
              ...this.$refs.basic.form,
              ...this.$refs.sale.form,
            });
            this.$message.success('添加成功！');
          }
          this.$router.push({ name: 'productList' });
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.product-detail {
  width: 100%;
  height: 100%;
  padding: 30px;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
  overflow: auto;
}

.steps {
  width: 60%;
  max-width: 800px;
}

.steps-content {
  margin: 20px 0;
  height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
